from django.core.paginator import Paginator, EmptyPage  # 分页
from django.http import JsonResponse  # 抛出ｊｓｏｎ数据
from django.shortcuts import render  # 返回渲染后的ＨｔｔｐＲｅｓｏｉｎｓｅ对象
from django.views import View  # ｄｊａｎｇｏ视图
from haystack.views import SearchView  # 搜索
from datetime import date  # 时间模块　
from apps.goods import models  # ｇｏｏｄｓ模块
from utils.goodsuitls import get_goods_specs, get_categories
from apps.goods.models import GoodsCategory, SKU  # ｇｏｏｄｓ模块
# from utils.goods import get_categories  # 商品频道
from apps.ad.models import ContentCategory  # 地区模块
from utils.goodsuitls import get_breadcrumb  # 频道与广告
from apps.goods.models import GoodsVisitCount  # 累加数量模块


class IndexView(View):
    def get(self, request):
        # 商品频道和分类
        try:
            categories = get_categories()
        except Exception as e:
            print(e)
            return {'code': 1, 'errmsg': '获取数据失败'}

        # 广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        print('contents', contents)
        return JsonResponse({'code': 0, 'errmsg': 'ok', "categories": categories, 'contents': list(contents)})


# 商品列表页
class ListView(View):
    def get(self, request, category_id):
        # １．接收参数
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        # ２．获取商品数据
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '商品数据错误'})

        # ２．1　面包屑
        breadcrumb = get_breadcrumb(category)
        # 面包屑排序
        try:
            skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '获取mysql数据错误'})

        # ２．2分页
        # skus 页数据　page_size 页总数
        paginator = Paginator(skus, page_size)
        # 2.3　每页数据
        page_skus = paginator.page(page)
        # ３　获取总页数
        total_page = paginator.num_pages

        # ４　合成数据格式
        list = []
        for sku in page_skus:
            list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
        })

        # 5　返回ｊｓｏｎ
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'count': total_page,
                             'list': list,
                             'breadcrumb': breadcrumb,
                             })


# 列表页热销排行
class HotGoodsView(View):
    def get(self, request, category_id):
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]

        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        return JsonResponse({'code': 200, 'errmsg': 'OK', 'hot_skus': hot_skus})


# 商品搜索
class MySearchView(SearchView):

    def create_response(self):
        context = self.get_context()
        data_list = []
        page_count = context['page'].paginator.num_pages
        print(context)
        for sku in context['page'].object_list:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_nums': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count,
            })
        print(sku)
        print(context)

        return JsonResponse({'code': 0, 'errmgs': 'ok', 'data_list': data_list, 'page_count': page_count}, safe=False)


# 商品详情
class DatailView(View):
    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 渲染页面
        context = {
            'caregories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku
        }

        return render(request, 'detail.html', context)


# 详情页分类商品访问量
class DetailVisitView(View):
    def post(self, request, category_id):
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        today_date = date.today()

        try:
            count_data = category.goodschannel_set.get(date=today_date)
        except:
            count_data = GoodsVisitCount()

        try:
            count_data.count += 1
            count_data.category = category
            count_data.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '新增失败'})

        return JsonResponse({'code': 0, 'errmsg': 'OK'})
